import { defineComponent, onMounted, reactive } from "vue";
import styles from "./resetPassword.module.less";
import { useStore as useUserStore } from "@/store/user";
import { useStore as useInfoStore } from "@/store/userinfo";
import { message } from "ant-design-vue";
import { InfoCircleOutlined } from "@ant-design/icons-vue";
import validateInstance from "@/libs/validate/validate";
import { $modifyPwd } from "@/api/account/account";
import { useRouter } from "vue-router";
export default defineComponent({
  name:'accountUserinfoChangePasswordResetPassword',
  setup() {
    const userStore = useUserStore();
    const infoStore = useInfoStore();
    const router = useRouter();
    const state = reactive({
      current: 1,
      steps: [
        {
          title: '验证身份',
        },
        {
          title: '修改密码登录'
        },
        {
          title: '完成'
        }
      ],
      img: '',
      form: {
        mobile: '',
        code: '',
        syncCode: '',
        oldPassword: '',
        newPassword: '',
        confirmPassword: '',
      },
      level: [],
      btn_text: '下一步',
    } as any)



    const oldPassword_check = async (_rule: any, value: string) => {
      if (value === '') {
        return Promise.reject('请输入老密码')
      }
    }

    const newPassword_check = async (_rule: any, value: string) => {
      if (value === '') {
        return Promise.reject('请输入新密码')
      }
    }

    const confirmPassword_check = async (_rule: any, value: string) => {
      if (value === '') {
        return Promise.reject('请再次输入密码')
      }
    }

    //表单验证
    const submitRules = {
      oldPassword: [{ required: true, validator: oldPassword_check, trigger: 'change' }],
      newPassword: [{ required: true, validator: newPassword_check, trigger: 'change' }],
      confirmPassword: [{ required: true, validator: confirmPassword_check, trigger: 'change' }],
    }

    //密码强度验证
    const passwordIntensity = () => {
      state.level = [];
      //效验字母
      const regex = /^[A-Za-z]+$/;
      //效验符号
      const regex1 = /^[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、]+$/;
      if (validateInstance.test(state.form.confirmPassword, 'number')) {
        state.level.push('low')
      } else if (regex.test(state.form.confirmPassword)) {
        state.level.push('low')
      } else if (regex1.test(state.form.confirmPassword)) {
        state.level.push('low')
      } else if (/^[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、0-9]+$/.test(state.form.confirmPassword)) {
        state.level.push('low')
        state.level.push('middle')
      } else if (/^[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、A-Za-z]+$/.test(state.form.confirmPassword)) {
        state.level.push('low')
        state.level.push('middle')
      } else if (/^[A-Za-z0-9]+$/.test(state.form.confirmPassword)) {
        state.level.push('low')
        state.level.push('middle')
      } else if (/^[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、0-9A-Za-z]+$/.test(state.form.confirmPassword)) {
        state.level.push('low')
        state.level.push('middle')
        state.level.push('high')
      }
    }

    //下一步
    const nextStep = () => {
      if (!state.form.oldPassword) {
        message.error('请输入老密码');
        return;
      }
      if (!state.form.newPassword) {
        message.error('请输入新密码');
        return;
      }
      if (state.form.newPassword !== state.form.confirmPassword) {
        message.error('密码不一致');
        return;
      }
      console.log(infoStore.passwordFlag);
      $modifyPwd({
        password: state.form.oldPassword,
        new_password: state.form.newPassword,
        repassword: state.form.confirmPassword,
        flag: infoStore.passwordFlag,
      }).then((res: any) => {
        infoStore.clearPasswordFlag();
        state.current = 2;
      }).catch((error:any) => {
        if (error.code === 403) { //验证标记失效或者不正确处理
          message.error('验证信息已失效，请重新验证身份');
          router.go(-1);
        }
      })
    }
    onMounted(()=>{
      if(!infoStore.passwordFlag){
        message.error('验证信息已失效，请重新验证身份');
        router.go(-1);
        return;
      }
    })
    return () => (
      <div class={styles.Authenticate}>
        <div class={styles.header}>修改登录密码</div>
        <div class={styles.container}>
          <a-steps current={state.current}>
            <a-step title={'验证身份'}></a-step>
            <a-step title={'修改登录密码'}></a-step>
            <a-step title={'完成'}></a-step>
          </a-steps>
          <div class={styles['form-box']}>
            {
              <a-form model={state.form} v-show={state.current === 1} rules={submitRules} label-col={{ style: { width: '90px' } }}>
                <a-form-item required label="老密码" name="oldPassword">
                  <a-input style={{ width: '210px' }} type="password" v-model:value={state.form.oldPassword} />
                </a-form-item>
                <a-form-item required label="新密码" name="newPassword">
                  <a-input style={{ width: '210px' }} type="password" v-model:value={state.form.newPassword} />
                </a-form-item>
                <div class={styles.tips}>
                  <InfoCircleOutlined />
                  <span>长度为8-20个字符</span>
                </div>
                <div class={styles.tips}>
                  <span>必须包含字母、数字和特殊字符（!@#$%^&*）</span>
                </div>
                <a-form-item required label="确认密码" name="confirmPassword">
                  <a-input style={{ width: '210px' }} type="password" v-model:value={state.form.confirmPassword} onBlur={() => { passwordIntensity() }} />
                </a-form-item>
                <div class={styles.intensity}>
                  <span class={[styles.line, state.level.includes('low') && styles.low]}>弱</span>
                  <span class={[styles.line, state.level.includes('middle') && styles.middle]}>中</span>
                  <span class={[styles.line, state.level.includes('high') && styles.high]}>强</span>
                </div>
              </a-form>
            }
            {
              <div class={styles.success} v-show={state.current === 2}>
                <span>登录密码更新成功</span>
              </div>
            }
            <div class={styles['nextStep-btn']} onClick={() => { nextStep() }} v-show={state.current !== 2}>{state.btn_text}</div>
          </div>
        </div>
      </div>
    )
  }
})